#include "AppDelegate.h"
#include "cocos2d.h"
#include "CCEventType.h"
#include "platform/android/jni/JniHelper.h"
#include <jni.h>
#include <android/log.h>

#define  LOG_TAG    "main"
#define  LOGD(...)  __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__)

using namespace cocos2d;

class JNIContext: public CallbackListener {
public:
	JNIContext(JNIEnv* env, jobject obj);

	~JNIContext();

	void shareViaFacebookCallback();
	void rateThisApplicationCallback();
private:
	JNIEnv *_env;
	jobject _obj;
};

extern "C" {

jint JNI_OnLoad(JavaVM *vm, void *reserved) {
	JniHelper::setJavaVM(vm);

	return JNI_VERSION_1_4;
}

void Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeInit(JNIEnv* env,
		jobject thiz, jint w, jint h) {
	if (!CCDirector::sharedDirector()->getOpenGLView()) {
		CCEGLView *view = CCEGLView::sharedOpenGLView();
		view->setFrameSize(w, h);

		JNIContext *context = new JNIContext(env, thiz);

		AppDelegate *pAppDelegate = new AppDelegate();

		pAppDelegate->setListener(context);

		CCApplication::sharedApplication()->run();
	} else {
		ccGLInvalidateStateCache();
		CCShaderCache::sharedShaderCache()->reloadDefaultShaders();
		ccDrawInit();
		CCTextureCache::reloadAllTextures();
		CCNotificationCenter::sharedNotificationCenter()->postNotification(
				EVENT_COME_TO_FOREGROUND, NULL);
		CCDirector::sharedDirector()->setGLDefaultValues();
	}
}



}
JNIContext::JNIContext(JNIEnv* env, jobject obj) {
	_env = env;
	_obj = obj;
}

JNIContext::~JNIContext() {

}
//com.android.app.funnyegg
void JNIContext::shareViaFacebookCallback() {
	jclass cls = _env->FindClass("com/adu/funnyegg/FunnyEgg");
	if (cls == NULL) {
		return;
	}
	jmethodID mid = _env->GetStaticMethodID(cls, "shareViaFacebook", "()V");
	if (mid == NULL) {
		return;
	}
	_env->CallStaticVoidMethod(cls, mid);
}

void JNIContext::rateThisApplicationCallback()
{
	jclass cls = _env->FindClass("com/adu/funnyegg/FunnyEgg");
	if (cls == NULL) {
		return;
	}
	jmethodID mid = _env->GetStaticMethodID(cls, "rateThisApp", "()V");
	if (mid == NULL) {
		return;
	}
	_env->CallStaticVoidMethod(cls, mid);
}
